package com.manong.config.security.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.manong.config.redis.RedisService;
import com.manong.entity.LoginLog;
import com.manong.entity.User;
import com.manong.service.LoginLogService;
import com.manong.utils.IpAddressUtil;
import com.manong.utils.JwtUtils;
import com.manong.utils.LoginResult;
import com.manong.utils.ResultCode;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 登录认证成功处理器
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private RedisService redisService;
    @Resource
    private LoginLogService loginLogService;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //响应编码格式
        response.setContentType("application/json;charset=utf-8");
        //获取当前登录用户信息
        User user = (User)authentication.getPrincipal();
        //生成token
        String token = jwtUtils.generateToken(user);
        //获取token过期时间
        long jwt = Jwts.parser().setSigningKey(jwtUtils.getSecret()).parseClaimsJws(token.replace("jwt_", ""))
                .getBody().getExpiration().getTime();
        //封装结果
        LoginResult loginResult = new LoginResult(user.getId(), ResultCode.SUCCESS, token, jwt);

        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(user.getUsername());
        loginLog.setStatus('0');
        loginLog.setIpaddr(IpAddressUtil.getClientIPv4(request).equals("0:0:0:0:0:0:0:1")?"127.0.0.1":IpAddressUtil.getClientIPv4(request));
        loginLog.setOs(request.getHeader("sec-ch-ua-platform").replace("\"",""));
        loginLog.setMsg("登录成功");
        loginLog.setLoginTime(new Date());
        loginLogService.save(loginLog); //记录登录成功日志

        //将对象转为json格式返回并消除循环引用
        String result = JSON.toJSONString(loginResult, SerializerFeature.DisableCircularReferenceDetect);
        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        out.write(result.getBytes(StandardCharsets.UTF_8));
        out.flush();
        out.close();
        String key = "token_" + token;
        redisService.set(key,token,jwtUtils.getExpiration()/1000);
    }
}
